package io.kljf.boot.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;


/**
 * @author katherine
 * @version 2020-12-01
 **/
public class JwtUtil {
    /**
     * 发布人
     */
    private static final String ISSUER = "kljf-boot";
    /**
     * 过期时间（单位：分钟）
     */
    public static final int EXPIRES_IN = 10;

    /**
     * 获得token中的信息
     * @param accessToken
     * @return
     */
    public static String getUsername(String accessToken) {
        // Reusable verifier instance
        DecodedJWT decodedJWT = JWT.decode(accessToken);
        // verity 自定义参数
        String username = decodedJWT.getClaim("username").asString();
        return username;
    }

    /**
     * 生成签名，10min后失效
     * @param username
     * @return
     */
    public static String generateToken(String username,String password) {
        Algorithm algorithm = Algorithm.HMAC256(password);
        long currentTime = System.currentTimeMillis();
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(new Date(currentTime))// 签发时间
                .withExpiresAt(new Date(currentTime + EXPIRES_IN * 1000 * 60))// 过期时间戳
                .withClaim("username", username)//自定义参数
                .sign(algorithm);
        return token;
    }

    public static boolean verify(String accessToken, String userName, String passWord) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(passWord);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", userName).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(accessToken);
            return true;
        }catch(Exception e){
            return false;
        }
    }
}
